package com.zhuxulin.tab.bluetooth;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;

import com.zhuxulin.tab.utils.LogUtils;

public class PlayMusic {
	private static final String TAG = PlayMusic.class.getSimpleName();
	private String palyPath = null;
//	"/mnt/sdcard/Music/1.mid";
	private Context context = null;
	private MediaPlayer player = null;
	private AudioManager manager = null;

	public PlayMusic(Context context) {
		this.context = context;
		player = new MediaPlayer();
		manager = (AudioManager) context.getApplicationContext()
				.getSystemService(Context.AUDIO_SERVICE);
	}
	public void setPlayFile(String fileName){
		this.palyPath=fileName;
		this.reset();
	}
	public void setPlayFile(File file){
		this.palyPath=file.getPath();
		this.reset();
	}
	private void reset(){
		player.reset();
		try {
			player.setDataSource(palyPath);
			player.prepare();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void play() {
		try {
			player.reset();
			player.setDataSource(palyPath);
			player.prepare();
			player.start();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void start() {
		if (player == null) {
			return;
		}
		if (!player.isPlaying()) {
			player.start();
		}
	}

	public void pause() {
		if (player == null)
			return;
		if (player.isPlaying()) {
			player.pause();
		}
	}

	public void stop() {
		if (player == null)
			return;
		if (player.isPlaying()) {
			player.stop();
		}
	}

	public void next() {
		if (player == null)
			return;
	}

	public void previous() {
		if (player == null)
			return;
	}

	public boolean isPlaying() {
		if (player == null)
			return false;
		return player.isPlaying();
	}

	public void bluetoothPlay() {
		LogUtils.i(TAG, "Bluetooth Play Music!");
		// manager.setMode(AudioManager.MODE_IN_CALL);
		manager.setStreamMute(AudioManager.STREAM_VOICE_CALL, true);
		manager.setBluetoothScoOn(true);
		// manager.setBluetoothA2dpOn(true);
		manager.startBluetoothSco();
	}
}
